package controlmercancias.gui.cliente;

import controlmercancias.gui.*;

import controlmercancias.excepciones.ForceExitException;
import controlmercancias.remoto.cliente.Cliente;
import controlmercancias.remoto.servidortren.ServidorTrenDemon;
import controlmercancias.util.Message;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.regex.Pattern;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

public class ComprobacionUsuarioCliente extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTextField nombreUsuario;
    private JPasswordField password;
    private JTextField ip;
    private JButton send;
    private boolean init = false;

    public ComprobacionUsuarioCliente() {
        KeyListener kl = new KeyAdapter() {

            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == '\n') {
                    send.doClick();
                }
            }
        };
        nombreUsuario = new JTextField(20);
        nombreUsuario.addKeyListener(kl);
        password = new JPasswordField(20);
        password.addKeyListener(kl);
        ip = new JTextField(10);
        ip.addKeyListener(kl);
        send = new JButton("Conectar");
        JPanel nombrePanel = new JPanel();
        nombrePanel.add(new JLabel("Nombre:"));
        nombrePanel.add(nombreUsuario);
        JPanel passwordPanel = new JPanel();
        passwordPanel.add(new JLabel("Password:"));
        passwordPanel.add(password);
        JPanel ipPanel = new JPanel();
        ipPanel.add(new JLabel("IP:"));
        ipPanel.add(ip);
        JPanel sendPanel = new JPanel();
        sendPanel.add(send);
        JPanel container = new JPanel();

        BoxLayout boxLayout = new BoxLayout(container, BoxLayout.Y_AXIS);
        container.setLayout(boxLayout);
        container.add(nombrePanel);
        container.add(passwordPanel);
        container.add(ipPanel);
        container.add(sendPanel);
        this.add(container);
        this.setTitle("Conexión cliente");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                try {
                    if (init) {
                        Cliente.salir();
                    }
                } catch (Exception ex) {
                }
            }
        });
        send.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                final WaitingJFrame w = new WaitingJFrame("Iniciando sesión...");
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        w.setVisible(true);
                    }
                });
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        String sip = ip.getText();
                        if (!comprobarIp(sip)) {
                            JOptionPane.showMessageDialog(ComprobacionUsuarioCliente.this, "La IP no es correcta", "Error", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        String nombre = nombreUsuario.getText();
                        try {
                            Cliente.createCliente(nombre, sip);
                            String ret = Cliente.validateUser();
                            if (ret.equals(Message.OK.toString())) {
                                init = true;
                                String p = "";
                                for (char s : password.getPassword()) {
                                    p += s;
                                }
                                ret = Cliente.validatePass(p);
                                if (ret.equals(Message.OK.toString())) {
                                    DatosTren dt = new DatosTren();
                                    ComprobacionUsuarioCliente.this.setEnabled(false);
                                    ComprobacionUsuarioCliente.this.setVisible(false);
                                    dt.setVisible(true);
                                } else {
                                    JOptionPane.showMessageDialog(ComprobacionUsuarioCliente.this, ret, "Error", JOptionPane.ERROR_MESSAGE);
                                    return;
                                }
                            } else {
                                JOptionPane.showMessageDialog(ComprobacionUsuarioCliente.this, ret, "Error", JOptionPane.ERROR_MESSAGE);
                                return;
                            }
                        } catch (ForceExitException ex) {
                            JOptionPane.showMessageDialog(ComprobacionUsuarioCliente.this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                            return;
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(ComprobacionUsuarioCliente.this, Message.IOException.toString(), "Error", JOptionPane.ERROR_MESSAGE);
                            return;
                        } finally {
                            w.setVisible(false);
                            w.setEnabled(false);
                            w.dispose();
                        }
                    }
                }).start();
            }
        });
        this.setSize(400, 200);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        this.setIconImage(ServidorTrenDemon.appIcon);
    }

    private static boolean comprobarIp(String ip) {
        String pattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
        return Pattern.matches(pattern, ip);
    }

    public static void main(String[] args) {
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
        }
        ComprobacionUsuarioCliente f = new ComprobacionUsuarioCliente();
        f.setVisible(true);
    }
}
